<!--
* @Description: gisMonitoring.vue gis监控
* @Author: 王燕欣
* @Date: 2024-09-25 15:20
-->

<template>
  <div class="public_container">
    <!-- 地图区域 -->
    <div id="gismap" class="ku_map_container">
    </div>
    <!-- 线路列表 -->
    <tabNav v-if="!routeParamState" ref="tabNavRef" :navOption="routerList" :active="activeRouterIndex" field="routeName" @click="routerCheckFun" @selectClick="routerSelectClick"></tabNav>

    <!-- 更多线路 -->
    <div class="ku_router_popup" v-if="moreRouterState">
      <div class="ku_button_list">
        <div class="ku_button_item" v-for="(item,index) in routerList" :key="index">
          <span class="ku_button" :class="index===activeRouterIndex?'active':''" @click="routerCheckFun(index)">{{ item.routeName }}</span>
        </div>
      </div>
    </div>
    <!-- 运行情况 -->
    <div class="ku_operation_status_container" v-if="!routeParamState">
      <span class="ku_button_primary ku_button" @click="showRouterVehicleList=true">
        选择车辆
      </span>
      <!-- 线路车辆列表 -->
      <div class="ku_vertical_container ku_realtime_bus_list ku_left_popup" v-if="showRouterVehicleList">
        <div class="ku_vertical_item" @click="zoomMapLayerFun">全部车辆</div>
        <div class="ku_vertical_list">
          <div class="ku_vertical_item" @click="selectDisplayVehicleClick(item.busId)" v-for="(item,index) in vehicleList" :key="index" :class="item.busId==trackBusId?'active':''"> {{item.busShowStr}} </div>
        </div>
        <div class="ku_vertical_item" @click="showRouterVehicleList=false">关闭</div>
      </div>

      <!-- 运行信息汇总 -->
      <div class="ku_operation_status_wrap">
        <div class="ku_operation_status_item" v-for="(item,index) in vehicleOperatingStatus" :key="index">
          <van-image round width="24px" height="24px" :src="item.imageUrl" />
          <span class="">{{ item.title }}</span>
          <span class="ku_operation_number">{{ item.number }}</span>
        </div>
        <template v-if="routeType == 1">
          <div class="ku_operation_status_item">
            <span class="">上行</span>
            <span class="ku_operation_number">{{ upstreamCount }}</span>
          </div>
          <div class="ku_operation_status_item">
            <span class="">下行</span>
            <span class="ku_operation_number">{{ downwardCount }}</span>
          </div>
        </template>
        <div class="ku_operation_status_item" v-else>
          <span class="">环行</span>
          <span class="ku_operation_number">{{ upstreamCount }}</span>
        </div>
      </div>
    </div>
    <!-- 右侧更多操作处理 -->
    <div class="ku_gis_right_more_operations" v-if="!routeParamState">
      <div class="ku_button_plain_primary ku_margin_bottom_15" @click="showStationStatusClick">
        显示站点
        <i class="ku_icon_active" v-if="lineVectorLayerConfig.stationStatus"></i>
      </div>
      <!-- 上下行 -->
      <template v-if="routeType == 1">
        <div class="ku_button_plain_primary ku_margin_bottom_6" @click="upDownRouterClick(item.type)" v-for="item in upDownRouterList" :key="item.type" :class="filterUpDownState=== item.type?'active':''">
          {{ item.text }}
        </div>
      </template>
      <div v-else class="ku_button_plain_primary ku_margin_bottom_6 active" @click="upDownRouterClick('all')">环形</div>
<!-- 
      <span class="ku_button_primary ku_button" @click="simulatedSideSearch">
        模拟搜索
      </span> -->
    </div>

    <busInfoPopup ref="busInfoPopupRef" :busOperationArray="busOperationInfo" @locatedBusFeatureClick="locatedBusFeatureCallback" @cancelPositioningCallback="unPositioningTracking"></busInfoPopup>
    <div class="gis_realtime_monitor_image">
      <img id="realtimeMonitorBusDirection" :src="vehicleOperatingList.direction" />
      <img id="realtimeMonitorBusIcon" :src="vehicleOperatingList.bus1" />
      <img id="realtimeMonitorBusPeccancyDirection" :src="vehicleOperatingList.alertDirection" />
      <img id="offLineFlg" :src="vehicleOperatingList.offLineFlg" />
      <img id="realtimeMonitorBusLocatedIcon" :src="vehicleOperatingList.busLocated" />
      <img id="realtimeMonitorPolyBackground" :src="vehicleOperatingList.polyBackground" />
      <img id="realtimeMonitorBusGreenIcon" :src="vehicleOperatingList.busGreen" />
      <img id="realtimeMonitorBusLocatedGreenIcon" :src="vehicleOperatingList.busLocatedGreen" />
    </div>
  </div>

</template>

<script>
import { isNaN } from "lodash";
import { Feature } from "ol";
import { LineString, Point } from "ol/geom";
import { Fill, Icon, Stroke, Style, Text } from "ol/style";
import CircleStyle from "ol/style/Circle";

import globalConfigs from "@/utils/globalConfigs";
import WebsocketComm from "@/utils/webSocketService";

import FlutterBridge from "@/utils/FlutterBridge";
import $store from '@/store'

import { Notify } from "vant";
import HiMap from "@/plugins/map/himap";
import tabNav from "@/components/TabNav.vue";

import busInfoPopup from "@/views/gis/components/busInfoPopup.vue"; // 车辆弹出详情

import gis_car_primary from "@/assets/images/gis/gis_car_primary.png";
import gis_car_off_line from "@/assets/images/gis/gis_car_off_line.png";
import gis_car_danger from "@/assets/images/gis/gis_car_danger.png";

import direction from "@/assets/images/gis/direction.png";
import bus1 from "@/assets/images/gis/bus1.png";
import alertDirection from "@/assets/images/gis/alertDirection.png";
import offLineFlg from "@/assets/images/gis/offLineFlg.png";

import busLocated from "@/assets/images/gis/busLocated.png";
import polyBackground from "@/assets/images/gis/polyBackground.png";
import busGreen from "@/assets/images/gis/busGreen.png";
import busLocatedGreen from "@/assets/images/gis/busLocatedGreen.png";

import { getAuthRouteListApi, getBusListByRouteIdApi } from "@/api/base";
import { getRouteStationLineApi } from "@/api/gis/realtime";

export default {
  name: "gisMonitoring",
  components: {
    tabNav,
    busInfoPopup,
  },
  props: {},

  data() {
    return {
      hiMap: null,
      mapLayer: {
        // trackVectorLayer: null, // 运行轨迹图层
        lineVectorLayer: null, // 线路轨迹图层
        busVectorLayer: null, // 车辆图层
        // peccancyVectorLayer: null, // 违规告警图层
        // speedVectorLayer: null, // 速度图层
        markerVectorLayer: null, // 标记图层
      },
      // 绘制线路地图相关信息
      lineVectorLayerConfig: {
        mainLineColor: "#23b723", // 主线路颜色
        subLineColor: "#1a9fff", // 副线路颜色
        stationStatus: true, // 设置是否显示站点信息
      },
      // 上下行状态
      upDownRouterList: [
        { type: "all", text: "上下行" },
        { type: "up", text: "上行" },
        { type: "down", text: "下行" },
      ],
      filterUpDownState: "all", // 筛选显示线路上下行

      routeParamState: false, // 路由是否传参

      routerList: [], // 线路列表
      moreRouterState: false, // 更多线路
      activeRouterIndex: 0,

      chooseRouteId: "", // 当前选择的线路id
      routeType: '',//线路类型 1上下行2环形
      vehicleList: [], // 线路下的车辆列表
      showRouterVehicleList: false, // 显示选择车辆
      trackBusId: "", // 当前选中车辆id
      busOperationInfo: [], //  当前车辆信息详情
      selectVehicleList: [], // 已选中的车辆Id
      busPositioningStatus: false, // 车辆定位是否开启

      currnetRouteStationLineList: [], // 获取线路站点信息

      // 车辆运行状态--引入图片
      vehicleOperatingStatus: [
        {
          title: "正常",
          imageUrl: gis_car_primary,
          number: "0",
        },
        {
          title: "异常",
          imageUrl: gis_car_danger,
          number: "0",
        },
        {
          title: "离线",
          imageUrl: gis_car_off_line,
          number: "0",
        },
      ],
      upstreamCount: 0,// 上行数量
      downwardCount: 0,// 下行车辆数量

      // canvas 线路上小车车辆图片
      vehicleOperatingList: {
        direction: direction,
        bus1: bus1,
        alertDirection: alertDirection,
        offLineFlg: offLineFlg, // 离线
        busLocated: busLocated,
        polyBackground: polyBackground,
        busGreen: busGreen,
        busLocatedGreen: busLocatedGreen,
      },

      webSocket: null,
    };
  },
  watch: {
    '$store.state.user.token': {
      handler(newVal) {
        // console.log('watch--监听-newVal--->store.token---', newVal);
        // console.log('watch--监听--old--->store.token---', oldVal);
        if (newVal) {
          console.log('token------>', $store.state.user.token);
          this.$nextTick(() => {
            this.initMapLayer();
            this.pageInit();
          });

        }
      },
      deep: true, //  深度监听
      immediate: true, // 立即执行
    },
    '$store.state.user.rightSideSearchGis': {
      handler(newVal) {
        // console.log('watch--监听-newVal---rightSideSearchGis---', newVal);
        // console.log('watch--监听--old-----rightSideSearchGis---', oldVal);
        if (newVal) {
          console.log('rightSideSearchGis------>');
          this.rightSideSearchGisCallback(newVal.data);
        }
      },
      deep: true, //  深度监听
      immediate: true, // 立即执行
    },

  },
  mounted() {

    // 有参数状态
    if (this.$route.query.routeId && this.$route.query.busId) {
      this.chooseRouteId = this.$route.query.routeId;
      this.trackBusId = this.$route.query.busId;
      this.routeParamState = true;
    }

    this.hiMap = new HiMap("gismap", {});
    // 判断是否是
    if (globalConfigs.IS_DEV) {
      this.$nextTick(() => {
        this.initMapLayer();
        this.pageInit();
      });
    } else {
      FlutterBridge.RequestFlutterBridge('getTokenFromFlutter');// 从flutter获取token
      window.FlutterBridgeCallback = FlutterBridge.FlutterBridgeCallback; // 监听flutter回掉方法
    }


  },
  methods: {
    /**
    * @Description: 模拟Flutter 数据 回调方法
    * @Author: 王燕欣
    * @Date: 2025-01-20 14:09
    */
    simulatedSideSearch() {
      console.log('模拟右上角搜索------simulatedSideSearch-----');
      let prames = {
        "method": "rightSideSearch",
        "data": {
          "car": {
            "busId": "2000000000000289684",
            "orgId": null,
            "routeIdList": null,
            "routeId": null,
            "cardId": "川AH2556",
            "busSelfId": "021115",
            "busShowStr": "021115|川AH2556",
            "status": null,
            "isTrolleyBus": null,
            "seatCount": null,
            "isSrt": null,
            "useCharacter": null,
            "passengers": null,
            "minimunTrolleyRate": null,
            "productId": null,
            "subCompanyId": null,
            "busCustomType": null,
            "selected": "1"
          },
          "route": {
            "routeId": "115",
            "routeName": "115",
            "routeType": "1",
            "stopMinutes": null,
            "crossTime": null,
            "crossTimestamp": null,
            "mainStationName": null,
            "mainEndStationName": null,
            "subStationName": null,
            "subEndStationName": null,
            "segmentCount": null,
            "sortNo": null,
            "displayOrder": 1,
            "segmentIdList": [
              "18242761",
              "18242762",
              "18237571",
              "18237572",
              "18242420",
              "18242421",
              "18243870",
              "18243871",
              "18243991",
              "18243992"
            ]
          }
        },
        "type": "gis"
      }
      prames = JSON.stringify(prames)
      FlutterBridge.FlutterBridgeCallback(prames)
    },

    /**
    * @Description: flutter 搜索回调事件
    * @Author: 王燕欣
    * @Date: 2025-01-20 14:50
    */
    rightSideSearchGisCallback(params) {
      // console.log('搜索回调事件------->', params);
      try {
        this.unPositioningTracking(); // 取消定位追踪
        //  this.activeRouterIndex = params; 

        this.chooseRouteId = params.route.routeId;
        this.routeType = params.route.routeType;// 线路类型 1上下行2环形
        this.trackBusId = params.car.busId; // 当前线路下选择的车辆
        this.showRouterVehicleList = false; // 关闭选择车辆
        this.$refs.busInfoPopupRef.assemblyHiden(); // 关闭显示

        //  console.log('搜索回调事件----chooseRouteId--->',  this.chooseRouteId);
        //  console.log('搜索回调事件---trackBusId---->',  this.trackBusId);
        // console.log('搜索回调事件---routerList---->', this.routerList);
        // 根据线路id获取匹配的线路角标
        for (let x = 0; x < this.routerList.length; x++) {
          const itemX = this.routerList[x];
          if (itemX.routeId === this.chooseRouteId) {
            this.activeRouterIndex = x;
          }
        }

        this.$nextTick(async () => {
          await this.getBusListByRouteIdFun(); // 根据线路ID获取车辆列表
          await this.getRouteStationLineFun(); // 获取线路站点
          this.drawRouteLine(); // 从新绘制线路站点
          this.initWebSocketRouteBusStateList(); // 获取线路下车辆信息列表

          // 判断是车辆列表中是否有车辆 如果有则开启定位
          for (let y = 0; y < this.vehicleList.length; y++) {
            const itemY = this.vehicleList[y];
            if (itemY.busId == this.trackBusId) {
              this.busPositioningStatus = true;
            }
          }
        });

      } catch (error) {
        console.error('搜索回调事件---error----', error);
      }
    },
    initMapLayer() {
      if (!this.mapLayer.lineVectorLayer) {
        this.mapLayer.lineVectorLayer = this.hiMap.createUserLayer(
          "line",
          {},
          {}
        );
      }
      if (!this.mapLayer.trackVectorLayer) {
        this.mapLayer.trackVectorLayer = this.hiMap.createUserLayer(
          "track",
          {},
          {}
        );
      }
      if (!this.mapLayer.markerVectorLayer) {
        this.mapLayer.markerVectorLayer = this.hiMap.createUserLayer(
          "marker",
          {},
          {}
        );
      }
      if (!this.mapLayer.busVectorLayer) {
        this.mapLayer.busVectorLayer = this.hiMap.createUserLayer(
          "bus",
          {},
          {}
        );
      }
      if (!this.mapLayer.peccancyVectorLayer) {
        this.mapLayer.peccancyVectorLayer = this.hiMap.createUserLayer(
          "peccancy",
          {},
          {}
        );
      }
    },


    /**
    * @Description: 地图缩放显示全部车辆
    * @Author: 王燕欣
    * @Date: 2025-01-05 21:52
    */
    zoomMapLayerFun() {
      // console.log("地图缩放显示全部车辆---->", this.hiMap);
      this.trackBusId = null;
      this.unPositioningTracking();
      this.$refs.busInfoPopupRef.assemblyHiden(); // 关闭显示
      this.hiMap.controlZoomLevel(12);

    },

    /**
     * @Description: 页面初始化
     * @Author: 王燕欣
     * @Date: 2024-09-27 11:38
     */
    async pageInit() {
      await this.getAuthRouteListFun();
      await this.getBusListByRouteIdFun();
      await this.getRouteStationLineFun();
      this.drawRouteLine();
      this.initWebSocketRouteBusStateList();
    },
    /**
     * @Description: 获取线路列表
     * @Author: 王燕欣
     * @Date: 2024-09-27 11:17
     */
    async getAuthRouteListFun() {
      const prames = {};
      await getAuthRouteListApi(prames).then((res) => {
        this.routerList = res.data;
        try {
          // 如果路由中有线路参数，车辆参数则获取对应线路及车辆监控
          if (!this.routeParamState) {
            this.activeRouterIndex = 0;
            this.chooseRouteId = res.data[0].routeId;
            this.routeType = res.data[0].routeType;
          } else {
            // 选中当前线路
            for (let x = 0; x < res.data.length; x++) {
              const itemX = res.data[x];
              if (itemX.routeId === this.chooseRouteId) {
                this.routeType = itemX.routeType;
                this.activeRouterIndex = x;
              }
            }
          }
        } catch (error) {
          Notify({ type: "warning", message: error });
        }
      });
    },
    /**
     * @Description:根据线路ID获取车辆列表
     * @Author: 王燕欣
     * @Date: 2024-09-27 11:36
     */
    async getBusListByRouteIdFun() {
      let prames = {
        routeId: this.chooseRouteId,
      };
      await getBusListByRouteIdApi(prames).then((res) => {
        this.vehicleList = res.data;
      });
    },

    /**
     * @Description: 线路选择
     * @Author: 王燕欣
     * @Date: 2024-09-30 17:43
     */
    routerCheckFun(params) {
      this.unPositioningTracking(); // 取消定位追踪
      this.activeRouterIndex = params;
      this.chooseRouteId = this.routerList[params].routeId;
      this.routeType = this.routerList[params].routeType; // 线路类型 1上下行2环形
      // console.log('线路选择------', this.routerList[params]);
      this.showRouterVehicleList = false; // 关闭选择车辆
      this.trackBusId = ""; // 清空当前线路下选择的车辆
      this.$refs.busInfoPopupRef.assemblyHiden(); // 关闭显示
      this.$nextTick(async () => {
        this.getBusListByRouteIdFun(); // 根据线路ID获取车辆列表
        await this.getRouteStationLineFun(); // 获取线路站点
        this.drawRouteLine(); // 从新绘制线路站点
        this.initWebSocketRouteBusStateList(); // 获取线路下车辆信息列表
      });
    },
    // 展开跟多线路
    routerSelectClick(params) {
      this.moreRouterState = params;
    },

    /**
     * @Description: 获取线路站点信息
     * @Author: 王燕欣
     * @Date: 2024-09-29 13:22
     */
    async getRouteStationLineFun() {
      this.mapLayer.lineVectorLayer.getSource().clear();
      // 获取线路站点
      await getRouteStationLineApi({
        routeId: this.chooseRouteId,
      }).then((res) => {
        this.currnetRouteStationLineList = res.data;
        this.drawRouteLine();
      });
    },

    /**
     * @Description: 绘制线路轨迹
     * @Author: 王燕欣
     * @Date: 2024-09-27 13:28
     */
    async drawRouteLine() {
      let _this = this;
      this.mapLayer.lineVectorLayer.getSource().clear();
      // 获取线路站点
      try {
        if (this.currnetRouteStationLineList.length > 0) {
          this.currnetRouteStationLineList.forEach((routeItem) => {
            if (routeItem.subRouteList) {
              routeItem.subRouteList.forEach((subRouteItem) => {
                if (subRouteItem.segmentList) {
                  let segmentList = subRouteItem.segmentList;
                  if (segmentList.length > 0) {
                    // 根据用户选择上下行，筛选线路显示
                    switch (this.filterUpDownState) {
                      case "up":
                        segmentList = segmentList.filter((item) => {
                          return item.runDirection === "1";
                        });
                        break;
                      case "down":
                        segmentList = segmentList.filter((item) => {
                          return item.runDirection === "2";
                        });
                        break;

                      default:
                        break;
                    }
                    _this.addRouteLine(this.lineVectorLayerConfig, segmentList);
                  }
                }
              });
            }
          });
        } else {
          console.warn("当前线路暂无站点信息-----", this.chooseRouteId);
        }
      } catch (error) {
        console.warn("当前线路暂无站点信息--error---", this.chooseRouteId);
      }

    },

    addRouteLine(config, list) {
      let featureArray = [];
      for (let j = 0; j < list.length; j++) {
        if (!list[j].stationList) continue;
        let coordinateList = [];
        // 筛选上下行

        for (let i = 0; i < list[j].stationList.length; i++) {
          let featureId =
            list[j].stationList[i].rSegmentSId ||
            list[j].segmentId + "-" + list[j].stationList[i].stationId;
          let stationInfo = list[j].stationList[i];
          if (
            !stationInfo ||
            isNaN(stationInfo.longitude) ||
            Number(stationInfo.longitude) < 5 ||
            isNaN(stationInfo.latitude) ||
            Number(stationInfo.latitude) < 5
          )
            continue;
          let coordinate = this.hiMap.transform([
            stationInfo.longitude,
            stationInfo.latitude,
          ]);
          let feature = new Feature({
            geometry: new Point(coordinate),
          });
          feature.setId(featureId);
          let imageStyle = new CircleStyle({
            radius: 6,
            fill: new Fill({
              color: "#ffffff",
            }),
            stroke: new Stroke({
              color:
                list[j].runDirection === "1"
                  ? config.mainLineColor
                  : config.subLineColor,
              width: 1,
            }),
          });
          let textStyle = new Text({
            textAlign: "left",
            font: "12px 宋体",
            style: {
              fontWeight: "bold", // 设置加粗
            },
            // text: stationInfo.serialCode + "-" + stationInfo.stationName,
            text: stationInfo.stationName, // 站点名称
            fill: new Fill({
              color: list[j].runDirection === "1" ? "#212121" : "#212121",
            }),
            padding: [5, 7, 5, 7],
            offsetX: 10,
            offsetY: 0,
            maxAngle: 0,
            rotation: 0,
          });
          if (config.stationStatus) {
            feature.setStyle(
              new Style({
                image: imageStyle,
                text: textStyle,
              })
            );
          } else {
            feature.setStyle(
              new Style({
                image: imageStyle,
              })
            );
          }
          featureArray.push(feature);
          let jwdList = [];
          if (stationInfo.jwd) {
            jwdList = stationInfo.jwd.split(";").map((item) => {
              return item && item.split(",");
            });
          }
          coordinateList = [
            ...coordinateList,
            [stationInfo.longitude, stationInfo.latitude],
            ...jwdList,
          ];
        }
        // 线路
        let transCoordinates = [];
        coordinateList.forEach((item) => {
          if (item && item.length === 2) {
            transCoordinates.push(this.hiMap.transform(item));
          }
        });
        let lineString = new LineString(transCoordinates);
        let lineFeature = new Feature({
          geometry: lineString,
        });
        lineFeature.setId(list[j].segmentId);
        lineFeature.setStyle(
          new Style({
            stroke: new Stroke({
              width: 4,
              color:
                list[j].runDirection === "1"
                  ? config.mainLineColor
                  : config.subLineColor,
            }),
          })
        );
        featureArray.push(lineFeature);
        // 起始站点
        let startMaker = new Feature({
          type: "icon",
          geometry: new Point(lineString.getFirstCoordinate()),
        });
        startMaker.setId(list[j].segmentId + "-start");
        startMaker.setStyle(
          new Style({
            image: new Icon({
              displacement: [0, 18],
              src: require("@/assets/images/gis/StartPoint.png")
            }),
            text: new Text({
              text: '起',
              textAlign: 'center',
              font: 'bold 12px 宋体',
              fill: new Fill({ color: '#13CD68' }),
              offsetX: 0,
              offsetY: -23
            })
          })
        );
        featureArray.push(startMaker);
        let endMaker = new Feature({
          geometry: new Point(lineString.getLastCoordinate()),
        });
        // 结束站点
        endMaker.setId(list[j].segmentId + "-end");
        endMaker.setStyle(
          new Style({
            image: new Icon({
              displacement: [0, 18],
              src: require("@/assets/images/gis/EndPoint.png")
            }),
            text: new Text({
              text: '终',
              textAlign: 'center',
              font: 'bold 12px 宋体',
              fill: new Fill({ color: '#FF5353' }),
              offsetX: 0,
              offsetY: -23
            })
          })
        );
        featureArray.push(endMaker);
        const position =
          lineString.getCoordinates()[
          Math.floor(lineString.getCoordinates().length / 2)
          ];
        // console.log(position, 'position定位点');
        this.hiMap.map.getView().setCenter(position);
      }

      this.mapLayer.lineVectorLayer.getSource().addFeatures(featureArray);
    },

    /**
     * @Description: 选择车辆事件
     * @Author: 王燕欣
     * @Date: 2024-09-27 17:38
     */
    selectDisplayVehicleClick(params) {
      console.log('选择车辆事件------selectDisplayVehicleClick---->')

      this.unPositioningTracking();
      this.trackBusId = params; // 设置 当前选中车辆id
      this.busOperationInfo = this.vehicleList.filter((item) => {
        return item.busId === params;
      }); // 当前车辆信息
      console.log("当前车辆信息-----0---", this.busOperationInfo);
      this.$refs.busInfoPopupRef.assemblyShow(); // 显示车辆详情
    },

    /**
     * @Description: 是否显示线路站点事件
     * @Author: 王燕欣
     * @Date: 2024-09-27 15:55
     */
    showStationStatusClick() {
      this.lineVectorLayerConfig.stationStatus =
        !this.lineVectorLayerConfig.stationStatus;
      this.drawRouteLine();
    },

    /**
     * @Description: 选择上下行事件
     * @Author: 王燕欣
     * @Date: 2024-09-27 16:46
     */
    upDownRouterClick(prames) {
      this.filterUpDownState = prames;
      this.drawRouteLine();
    },

    /**
     * @Description: 筛选出车辆状况
     * @Author: 王燕欣
     * @Date: 2024-09-30 18:03
     */
    processingBusRunningState(params) {
      // console.log('筛选出车辆状况---->',params)
      if (!params) {
        return
      }
      // 正常 normal
      let normal = params.filter((item) => {
        return item.offLineFlg === "0" && item.busViolateFlg === "0";
      });
      let abnormal = params.filter((item) => {
        return item.offLineFlg === "0" && item.busViolateFlg === "1";
      });
      let offLine = params.filter((item) => {
        return item.offLineFlg !== "0";
      });
      this.vehicleOperatingStatus[0].number = normal.length;
      this.vehicleOperatingStatus[1].number = abnormal.length; // 异常
      this.vehicleOperatingStatus[2].number = offLine.length;

      // 下行 - 主发，上行 - 副发  1-主站发车运行，2-副站发车运行，3-停主站，4-停副站，5-非营运，6-停运")
      this.upstreamCount = params.filter((item) => {
        return item.busStatus === "1";
      }).length;
      this.downwardCount = params.filter((item) => {
        return item.busStatus === "2";
      }).length;
    },

    /**
     * @Description: 线路车辆情况
     * @Author: 王燕欣
     * @Date: 2024-09-28 10:37
     */
    /**
     * 初始化websocket连接
     */
    initWebSocketRouteBusStateList() {
      console.log("initWebSocket------onopen---->");
      if (!this.chooseRouteId) return;
      let _this = this;
      let url =
        globalConfigs.WS_GIS_BASE_API +
        `/gis/realtimepush/realtime/work22?token=2345&pushAllDataFlag=1`;
      if (this.webSocket != null) {
        this.webSocket.close();
        this.webSocket = null;
      }
      this.webSocket = new WebsocketComm({
        url: url,
      });
      this.webSocket.onopen = () => {
        console.log("initWebSocket------onopen---->", url);
        let param = {
          // routeIdList: ['1000102','507'],
          routeIdList: [this.chooseRouteId],
        };
        console.log("initWebSocket------param---->", param);
        this.$nextTick(() => {
          if (this.webSocket != null) {
            this.webSocket.send(JSON.stringify(param));
          }
        });
      };
      this.webSocket.onmessage = function (res) {
        if (res) {
          //websocket出参数据，更新动态数据
          _this.addBusFeature(res[_this.chooseRouteId]);
          _this.processingBusRunningState(res[_this.chooseRouteId]);
        }
      };
    },
    /**
     * @Description: 设置车辆图层
     * @Author: 王燕欣
     * @Date: 2024-09-29 14:02
     */
    addBusFeature(busArrayParams) {
      // 处理数据 上行下行车辆数据
      let busArray = busArrayParams;

      if (this.routeParamState) {
        busArray = busArray.filter((item) => {
          return item.busId === this.trackBusId;
        })
      }
      // 根据用户选择上下行，筛选
      switch (this.filterUpDownState) {
        case "up":
          busArray = busArrayParams.filter((item) => {
            return item.busStatus === "1";
          })
          break;
        case "down":
          busArray = busArrayParams.filter((item) => {
            return item.busStatus === "2";
          })
          break;
        default:
          break;
      }

      try {
        // 当前选择车辆运行信息
        if (this.trackBusId) {
          let operationInfo = busArray.filter((item) => {
            return item.busId === this.trackBusId;
          })[0];
          this.busOperationInfo = this.vehicleList.filter((item) => {
            return item.busId === this.trackBusId;
          });
          if (this.busOperationInfo > 0) {
            this.busOperationInfo[0].operationInfo = operationInfo;
            this.$refs.busInfoPopupRef.wsCurrentBusOperationInfo(
              this.busOperationInfo
            ); // 显示车辆详情
          }

          if (this.routeParamState) {
            this.busPositioningStatus = true;
          }
          this.locatedBusFeature(operationInfo);
        }

        if (!this.hiMap && !this.mapLayer.busVectorLayer) return;
        let count = 0;
        if (!this.isBusCluster) {
          count = this.mapLayer.busVectorLayer.getSource().getFeatures().length;
          this.mapLayer.busVectorLayer.getSource().clear();
        } else {
          count = this.mapLayer.busVectorLayer
            .getSource()
            .getSource()
            .getFeatures().length;
          this.mapLayer.busVectorLayer.getSource().getSource().clear();
        }
        if (!busArray && busArray.length === 0) return;
        let featureList = [];
        for (let i = 0; i < busArray.length; i++) {
          let busInfo = busArray[i];
          if (!busInfo) continue;
          // 正式
          if (
            isNaN(busInfo.gpsLong) ||
            Number(busInfo.gpsLong) < 5 ||
            isNaN(busInfo.gpsLat) ||
            Number(busInfo.gpsLat) < 5
          )
            continue;
          let coordinate = this.hiMap.transform([
            busInfo.gpsLong,
            busInfo.gpsLat,
          ]);
          let feature = new Feature({
            geometry: new Point(coordinate),
          });
          feature.setId(busInfo.busId);
          feature.set("data", busInfo);
          feature.set("popup", true);
          if (!this.isBusCluster) {
            let angle = busInfo.gpsAngle || 0;
            feature.setStyle(
              new Style({
                image: new Icon({
                  img: this.drawBusImage(
                    angle,
                    this.locatedBusId === busInfo.busId,
                    busInfo
                  ),
                  imgSize: [52, 52],
                }),
                // 隐藏绘制白色边框车牌号；

                text: new Text({
                  placement: "point",
                  textAlign: "left",
                  font: "14px 宋体",
                  text: busInfo.busShowName,
                  fill: new Fill({ color: "#404ed0" }),
                  offsetX: -(busInfo.busShowName.length * 4),
                  offsetY: angle > 135 && angle < 235 ? 36 : 28,
                  maxAngle: 0,
                  rotation: 0,
                  backgroundFill: new Fill({ color: "#f8f9fe" }),
                  backgroundStroke: new Stroke({
                    color: "#404ed0",
                    width: 1,
                    lineCap: "round",
                  }),
                  padding: [2, 2, 2, 2],
                }),
              })
            );
          }
          featureList.push(feature);
          if (this.locatedBusId === busInfo.busId) {
            if (this.changeMapCenter) {
              this.hiMap.map.getView().setCenter(coordinate);
            }
            this.changeMapCenter = false;
          }
        }
        if (featureList.length > 0) {
          if (!this.isBusCluster) {
            this.mapLayer.busVectorLayer.getSource().addFeatures(featureList);
          } else {
            this.mapLayer.busVectorLayer
              .getSource()
              .getSource()
              .addFeatures(featureList);
          }
          if (count === 0 && !this.locatedBusId) {
            this.hiMap.map
              .getView()
              .setCenter(featureList[0].getGeometry().getCoordinates());
          }
        }
      } catch (error) {
        console.error('设置车辆图层-----', error, busArray)
      }
    },
    /**
     * 绘制车辆图标
     */
    drawBusImage(rotate, isLocated, busInfo) {
      const canvas = document.createElement("canvas"); //document.querySelector("#realtimeMonitorBusCanvas");
      canvas.width = 52;
      canvas.height = 52;
      const ctx = canvas.getContext("2d");
      if (isLocated) {
        const img3 = document.querySelector("#realtimeMonitorBusLocatedIcon");
        if (img3) {
          ctx.drawImage(img3, 0, 0);
        }
      }
      let imgSelector = "realtimeMonitorBusDirection";
      // 违规
      if (busInfo && busInfo.busViolateFlg === "1") {
        imgSelector = "realtimeMonitorBusPeccancyDirection";
      }
      // 离线
      if (busInfo && (busInfo.offLineFlg === "1" || busInfo.offLineFlg === "9")) {
        imgSelector = "offLineFlg";
      }

      const img = document.querySelector("#" + imgSelector);
      if (img) {
        // img.setAttribute('crossOrigin', 'Anonymous');
        // 平移转换，改变画笔的原点位置为画布的中心点
        ctx.translate(canvas.width / 2, canvas.height / 2);
        // 旋转转换，改变画笔的旋转角度
        ctx.rotate((rotate * Math.PI) / 180);
        // 调用绘制图片的方法把图片绘制到canvas中
        ctx.drawImage(img, -img.width / 2, -img.height / 2);
        // 还原坐标系
        ctx.translate(0, 0);
        ctx.rotate(-rotate * (Math.PI / 180));
        // 使用 restore()进行恢复
        ctx.restore();
      }
      const img2 = document.querySelector("#realtimeMonitorBusIcon");
      if (img2) {
        ctx.drawImage(img2, -img2.width / 2, -img2.height / 2);
      }
      // 非营运
      if (busInfo && busInfo.busStatus === "5") {
        // let runTypeObj = this.searchRunTypeList.find(item => item.itemValue === busInfo.busOperateCondType);
        // if (runTypeObj && runTypeObj.itemKeySimple) {
        //   ctx.beginPath();
        //   ctx.fillStyle = '#58B02B';
        //   ctx.strokeStyle = '#58B02B';
        //   ctx.lineJoin = 'round';  //交点设置成圆角
        //   ctx.lineWidth = 4;
        //   ctx.strokeRect(4, -20, 14, 14);
        //   ctx.fillRect(6, -18, 12, 12);
        //   ctx.stroke();
        //   ctx.closePath();
        //   ctx.font = '14px 微软雅黑';
        //   ctx.fillStyle = '#fff';
        //   ctx.fillText(runTypeObj.itemKeySimple, 4, -8);
        // }
      }
      ctx.imageSmoothingEnabled = true;
      ctx.imageSmoothingQuality = "high";
      return canvas;
    },
    /**
     * 绘制车辆图标 -聚集
     */
    drawClusterBusImage(rotate, isLocated, busCount, busInfo) {
      const canvas = document.createElement("canvas"); //document.querySelector("#realtimeMonitorBusCanvas");
      canvas.width = 52;
      canvas.height = 52;
      const ctx = canvas.getContext("2d");
      if (isLocated) {
        const img3 = document.querySelector("#realtimeMonitorBusLocatedIcon");
        if (img3) {
          ctx.drawImage(img3, 0, 0);
        }
      }
      let imgSelector = "realtimeMonitorBusDirection";
      // 违规
      if (busInfo && busInfo.peccancyType) {
        imgSelector = "realtimeMonitorBusPeccancyDirection";
      }
      const img = document.querySelector("#" + imgSelector);
      if (img) {
        // img.setAttribute('crossOrigin', 'Anonymous');
        // 平移转换，改变画笔的原点位置为画布的中心点
        ctx.translate(canvas.width / 2, canvas.height / 2);
        // 旋转转换，改变画笔的旋转角度
        ctx.rotate((rotate * Math.PI) / 180);
        // 调用绘制图片的方法把图片绘制到canvas中
        ctx.drawImage(img, -img.width / 2, -img.height / 2);
        // 还原坐标系
        ctx.translate(0, 0);
        ctx.rotate(-rotate * (Math.PI / 180));
        // 使用 restore()进行恢复
        ctx.restore();
      }
      const img2 = document.querySelector("#realtimeMonitorBusIcon");
      if (img2) {
        ctx.drawImage(img2, -img2.width / 2, -img2.height / 2);
      }
      const img4 = document.querySelector("#realtimeMonitorPolyBackground");
      if (img4) {
        ctx.drawImage(img4, -img4.width / 2 + 10, -img4.height / 2 - 10);
      }
      ctx.font = "12px 微软雅黑";
      ctx.fillStyle = "#fff";
      ctx.fillText(busCount, busCount > 9 ? 3 : 5, -5);
      return canvas;
    },

    /**
     * @Description: 定位车辆位置
     * @Author: 王燕欣
     * @Date: 2024-09-29 15:16
     */
    locatedBusFeatureCallback() {
      // 开启车辆定位
      this.busPositioningStatus = true;
    },
    /**
     * @Description: 取消定位追踪
     * @Author: 王燕欣
     * @Date: 2024-09-30 17:47
     */
    unPositioningTracking() {
      this.busPositioningStatus = false;
      this.mapLayer.markerVectorLayer.getSource().clear();
    },
    /**
    * @Description:车辆定位攻方法
    * @Author: 王燕欣
    * @Date: 2024-10-22 11:12
    */
    locatedBusFeature(busInfo) {

      if (!this.busPositioningStatus) {
        return;
      }
      let ft = this.mapLayer.markerVectorLayer
        .getSource()
        .getFeatureById(busInfo.busId + "-marker");
      if (!this.hiMap && !this.mapLayer.markerVectorLayer) return;
      this.mapLayer.markerVectorLayer.getSource().clear();
      if (
        isNaN(busInfo.gpsLong) ||
        Number(busInfo.gpsLong) < 5 ||
        isNaN(busInfo.gpsLat) ||
        Number(busInfo.gpsLat) < 5
      ) {
        return;
      }
      let coordinate = this.hiMap.transform([busInfo.gpsLong, busInfo.gpsLat]);
      this.hiMap.map.getView().setCenter([busInfo.gpsLong, busInfo.gpsLat]); // 设置中心点
      if (!ft) {
        this.hiMap.map.getView().animate({
          center: coordinate, // 中心点
          duration: 10, // 缩放持续时间，默认不需要设置
        });
      }
      let radius = 4; // radius一定要放在监听事件外面
      let opacity = 1; // 波纹的透明度
      let feature = new Feature({
        name: busInfo.busId,
        geometry: new Point(coordinate),
      });
      feature.setId(busInfo.busId + "-marker");
      this.mapLayer.markerVectorLayer.getSource().addFeature(feature);
      this.hiMap.map.on("postcompose", () => {
        // 给地图绑定事件，地图渲染后触发
        opacity = (25 - radius) / 25 + 0.3; // 不透明度 radius为0时，不透明；radius为25时，透明
        feature.setStyle(
          new Style({
            image: new CircleStyle({
              radius: radius,
              fill: new Fill({
                color: "rgba(255, 0, 0, 0.2)",
              }),
              stroke: new Stroke({
                color: "rgba(255, 0, 0, " + opacity + ")", // 通过rgba控制波纹的产生和消失
                width: 4,
              }),
            }),
          })
        );
        radius = radius + 0.3 >= 25 ? 1 : radius + 0.3;
      });
      this.hiMap.map.render();
    },
  },
  /**
   * @Description: 检查车辆图标是否超出可视范围
   * @Author: 王燕欣
   * @Date: 2024-09-29 15:19
   */
  checkFeatureInView: function ([lng, lat]) {
    let viewArea = this.hiMap.map
      .getView()
      .calculateExtent(this.hiMap.map.getSize());
    if (isNaN(lng) || Number(lng) < 5 || isNaN(lat) || Number(lat) < 5) return;
    let coordinate = this.hiMap.transform([lng, lat]);
    if (
      coordinate[0] <= Math.min(viewArea[0], viewArea[2]) ||
      coordinate[0] >= Math.max(viewArea[0], viewArea[2]) ||
      coordinate[1] <= Math.min(viewArea[1], viewArea[3]) ||
      coordinate[1] >= Math.max(viewArea[1], viewArea[3])
    ) {
      this.hiMap.map.getView().setCenter(coordinate);
    }
  },
};
</script>
<style lang="sass" scoped>
</style>
